package com.hsyt.pfc.support.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static HttpClient httpClient = HttpClientBuilder.create().build();

    /**
     * 获取webcontext完整路径
     *
     * @param request
     * @return
     */
    public static String getBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }

    /**
     * 解析出url参数中的键值对 如 "index.JSP?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> urlRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit = null;

        String strUrlParam = truncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        // 每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    // 只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }

        return strAllParam;
    }

    /**
     * 发送Post请求,  JSON串参数
     *
     * @throws ClientProtocolException
     * @throws IOException
     */
    //------------------------------------------------------------------
    public static String postForJson(String url, String json) throws ClientProtocolException, IOException {
        return postForJson(url, json, 0, 0, 0);
    }

    /**
     * 发送Post请求,  JSON串参数
     *
     * @throws ClientProtocolException
     * @throws IOException
     */
    //------------------------------------------------------------------
    public static String postForJson(String url, String json, int poolTimeout, int connectionTimeout, int socketTimeout)
            throws ClientProtocolException,
            IOException {
        log.debug("====>http请求-->请求地址:" + url);
        String resultJson = "";

        //请求头
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");

        StringEntity entity = new StringEntity(json, Charset.forName("UTF-8"));
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        if (poolTimeout > 0 && connectionTimeout > 0 && socketTimeout > 0) {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(poolTimeout).setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectionTimeout).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
        }
        //发起请求
        HttpResponse response = httpClient.execute(httpPost);
        int httpStatus = response.getStatusLine().getStatusCode();
        if (httpStatus != 200) {
            return resultJson;
        }

        log.debug("====>http请求-->返回状态:" + response.getStatusLine().getReasonPhrase());

        //结果转换成json
        HttpEntity httpEntity = response.getEntity();
        httpEntity.getContent();
        resultJson = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));

        log.debug("====>http请求-->返回字符串:" + resultJson);
        return resultJson;
    }

    public static String getForJson(String url) throws IOException {
        log.debug("====>http请求-->请求地址:" + url);
        String resultJson = "";
        //请求头
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Accept", "application/json");
        //发起请求
        HttpResponse response = httpClient.execute(httpGet);
        int httpStatus = response.getStatusLine().getStatusCode();
        if (httpStatus != 200)
            return resultJson;
        log.debug("====>http请求-->返回状态:" + response.getStatusLine().getReasonPhrase());
        //结果转换成json
        HttpEntity httpEntity = response.getEntity();
        httpEntity.getContent();
        resultJson = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
        log.debug("====>http请求-->返回字符串:" + resultJson);
        return resultJson;
    }

    /**
     * 发送Http Post请求
     *
     * @param url : URL路径
     * @param map : 参数
     * @return
     */
    public static String sendHttpPostRequest(String url, Map<String, Object> map) {

        return null;
    }

    /**
     * 发送 post请求 发送xml数据
     * @param url 地址
     * @param paramsXml 参数(格式 Xml)
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String postForXml(String url, String paramsXml) throws ClientProtocolException, IOException {
        log.debug("====>http请求-->请求地址:" + url);
        String resultJson = "";
        // 设置参数
        if (paramsXml != null && paramsXml.trim().length() > 0) {
            //请求头
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "text/xml; charset=utf-8");
            httpPost.setHeader("Accept", "text/xml");

            StringEntity entity = new StringEntity(paramsXml, Charset.forName("UTF-8"));
            entity.setContentType("text/xml");
            httpPost.setEntity(entity);
            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setSocketTimeout(0)
                        .setConnectTimeout(0).build();
            httpPost.setConfig(requestConfig);
            //发起请求
            HttpResponse response = httpClient.execute(httpPost);
            int httpStatus = response.getStatusLine().getStatusCode();
            if (httpStatus != 200) {
                return resultJson;
            }
            log.debug("====>http请求-->返回状态:" + response.getStatusLine().getReasonPhrase());
            //结果转换成json
            HttpEntity httpEntity = response.getEntity();
            httpEntity.getContent();
            resultJson = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
            log.debug("====>http请求-->返回字符串:" + resultJson);
        }
        return resultJson;
    }

}
